import path from 'path'
import { fileURLToPath } from 'url'
import ts from 'rollup-plugin-typescript2'
import replace from '@rollup/plugin-replace'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
if (!process.env.TARGET) {
  throw new Error('TARGET package must be specified via --environment flag.')
}
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, process.env.TARGET)
const resolve = p => path.resolve(packageDir, p)
import fs from 'fs'
const pkg = JSON.parse(fs.readFileSync(resolve('package.json'), 'utf-8'))
const name = path.basename(packageDir)
const outputConfigs = {
  'esm-bundler': {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: 'es'
  },
  cjs: {
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  global: {
    file: resolve(`dist/${name}.global.js`),
    format: 'iife'
  }
}
const defaultFormats = ['esm-bundler', 'cjs']
const packageFormats = defaultFormats
const packageConfigs = packageFormats.map(format => createConfig(format))
export default packageConfigs
function createConfig(format) {
  const output = outputConfigs[format]
  
  return {
    input: resolve('src/index.ts'),
    output,
    plugins: [
      replace({
        __DEV__: format === 'global' ? 'false' : 'process.env.NODE_ENV !== "production"',
        __VERSION__: JSON.stringify(pkg.version),
        preventAssignment: true
      }),
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json')
      }),
      nodeResolve(),
      commonjs()
    ]
  }
}